/*
    Copyright 2010 Northbranchlogic, Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.norbl.runjrun;

import com.norbl.util.*;
import java.lang.reflect.*;
import com.norbl.runjrun.exception.*;

/** Base for 'param' classes. These are classes that encapsulate
 *  parameter sets. 'Param' classes are designed so that parameters
 *  can be expressed as strings. String representations of parameters
 *  are needed to pass user data to EC2 instances and to create
 *  SQS messages.
 *
 * @author Barnet Wagman
 */
abstract public class AbstractParams {
    
    abstract protected void checkForRequiredParams();

    void setParams(String message,Field[] flds,boolean allowMissing) {
        try {
            PropertyList pl = PropertyList.parseTextForm(message);

            for ( Field f : flds ) {
                f.setAccessible(true);
                int mods = f.getModifiers();
                if ( !Modifier.isStatic(mods) ) {                    
                    Property p = pl.getProperty(f.getName());                    
                    if ( p != null ) f.set(this,p.value);
                    else if ( !allowMissing )
                        throw new MissingParameterException(f.getName() +
                                    " is missing.");
                }
            }
        }
        catch(IllegalAccessException iax) { throw new RuntimeException(iax); }        
    }

    protected String toMessageString(Field[] flds) {
        
        try {
            PropertyList pl = new PropertyList();

            for (Field f : flds) {
                f.setAccessible(true);
                int mods = f.getModifiers();
                if ( !Modifier.isStatic(mods) ) {
                    String name = f.getName();
                    Object val = f.get(this);
                    if ( val != null ) {
                        pl.add(name, val);
                    }
                }
            }
            return(pl.toTextForm());
        }
        catch(IllegalAccessException iax) { throw new RuntimeException(iax); }
    }
  
}
